<template>
  <div class="login-container">
    <div class="bg-image"/>
    <div class="custom">
      <img class="login-box" src="../../assets/login-box.png" alt="">
    </div>

    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
      <h3 class="title">
        <img class="admin-logo" style="width: 30%;" src="../../assets/logo.png" alt="">
        <h4>{{ loginTitleName }}</h4>
      </h3>
      <el-form-item prop="username">
        <span class="svg-container svg-container_login">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          v-model="loginForm.username"
          name="username"
          type="text"
          class="username"
          auto-complete="off"
          placeholder="用户名"
          @keyup.enter.native="handleLogin" />
      </el-form-item>
      <el-form-item prop="password">
        <span class="svg-container svg-container_pwd">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          v-model="loginForm.password"
          :type="pwdType"
          name="password"
          auto-complete="on"
          placeholder="登录密码"
          @keyup.enter.native="handleLogin" />

        <span class="show-pwd" @click="showPwd">
          <svg-icon icon-class="eye" />
        </span>
      </el-form-item>
      <!--<el-form-item prop="db" class="account" >
        <el-select v-model="loginForm.db" clearable filterable placeholder="请选择账套" style="width: 100%;" @change="selectZT" >
         <el-option
            v-for="item in accountList"
            :key="item[1]"
            :label="item[0]"
            :value="item[1]"/>
          <el-option label="报价系统" value="GenDB" />
        </el-select>
      </el-form-item>-->

      <el-form-item>
        <el-button
          :loading="loading"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin">
          登录
        </el-button>
      </el-form-item>

      <el-form-item style="border:none; float: right; margin-top: -12px;">
        <span class="forgot" @click="forgotPwd" >忘记密码 </span>
      </el-form-item>
    </el-form>

    <!-- 注册 -->
    <vxe-modal v-model="addregisterModal" :loading="vxeloading" :position="{top: 120, }" title="忘记密码" width="25%" min-width="300" min-height="600" resize remember destroy-on-close>
      <vxe-form ref="formRef" :data="form" :rules="formRules" align="center" title-width="100" title-align="right" @submit="submitEvent">
        <vxe-form-item :item-render="{}" :span="24" align="center" title="账号" field="name">
          <template #default="{ data }">
            <vxe-input v-model="data.name" placeholder="请输入账号" clearable/>
          </template>
        </vxe-form-item>

        <vxe-form-item :item-render="{}" :span="24" align="center" title="手机号" field="phone">
          <template #default="{ data }">
            <vxe-input v-model="data.phone" placeholder="请输入手机号" clearable/>
          </template>
        </vxe-form-item>

        <vxe-form-item :item-render="{}" :span="16" align="center" title="验证码" field="fcode">
          <template #default="{ data }">
            <vxe-input v-model="data.fcode" placeholder="请输入验证码" clearable />
          </template>
        </vxe-form-item>
        <vxe-form-item :item-render="{}" :span="8" align="center" >
          <template #default="{ data }">
            <el-button :disabled="disabled" type="success" @click.stop="getCode">{{ getCodeText }}</el-button>
            <!-- <el-button v-show="!show" type="success" >{{ count }}(s)后重新获取</el-button> -->
          </template>
        </vxe-form-item>

        <vxe-form-item :item-render="{}" :span="24" align="center" title="新密码" field="pass">
          <template #default="{ data }">
            <vxe-input :type="pwdType" v-model="data.pass" placeholder="请输入新密码" clearable/>
          </template>
        </vxe-form-item>
        <vxe-form-item :item-render="{}" :span="24" align="center" title="确认新密码" field="newpass">
          <template #default="{ data }">
            <vxe-input :type="pwdType" v-model="data.newpass" placeholder="请输入确认新密码" clearable>
              <span class="show-pwd" @click="showPwd">
                <svg-icon icon-class="eye" />
              </span>
            </vxe-input>
          </template>
        </vxe-form-item>

        <vxe-form-item :span="24" align="center" title-align="left">
          <template #default>
            <vxe-button type="submit">提交</vxe-button>
            <!-- <vxe-button type="reset">重置</vxe-button> -->
          </template>
        </vxe-form-item>

      </vxe-form>
    </vxe-modal>

  </div>

</template>

<script>
import { clearStorage, accountingMode, getsmsCode, UpdateSmsPass } from '../../api/login'
import { jichuData, getCSData } from '../../api/salary'
import { getUserName } from '@/utils/auth'

export default {
  name: 'Login',
  inject: ['globalDb'],
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入用户名'))
      } else {
        callback()
      }
    }
    const validatepassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }

    return {
      addregisterModal: false,
      form: {
        name: '',
        fcode: '',
        pass: '',
        newpass: '',
        phone: ''
      },
      formRules: {
        name: [
          { required: true, message: '请输入账号' }
        ],
        phone: [
          { required: true, message: '请输入手机号' },
          { max: 11, message: '手机号长度11个字符' }
        ],
        fcode: [
          { required: true, message: '请输入验证码' }
        ],
        pass: [
          { required: true, message: '请输入新密码' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符' }

        ],
        newpass: [
          { required: true, message: '请输入确认密码' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符' },
          { validator({ itemValue, data }) {
            // 自定义校验
            var qrpass = /^[A-Za-z0-9]+$/
            if (!qrpass.test(itemValue)) {
              return new Error('英文数字 ')
            } else if (itemValue !== data.pass) {
              return (new Error('两次输入密码不一致!'))
            }
          }
          }

        ]

      },
      vxeloading: false,
      show: true,
      count: '',
      timer: null,
      disabled: false,
      getCodeText: '获取验证码',

      loginForm: {
        // 账号密码 先默认
        username: '',
        password: '',
        db: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatepassword }],
        db: [{ required: true, message: '请选择账套', trigger: 'change' }]
      },
      loading: false,
      pwdType: 'password',
      listLoading: false,
      accountList: [],
      loginTitleName: '玉柴船动子系统'
    }
  },
  created() {
    // 默认GenDB
    // this.loginForm.db = 'GenDBTest'
    // this.globalDb.db = 'GenDBTest'
    this.loginForm.db = 'GenDB'
    this.globalDb.db = 'GenDB'
    this.globalDb.ztnamedb = this.loginTitleName
    // this.getAccountingMode()
    this.loginForm.username = getUserName()
    // console.log(username, ' username 222')
    // 参数
    this.getCSData()
    // 配置
    this.getConfig()
  },
  mounted() {

  },
  methods: {
    // 弹框
    forgotPwd() {
      this.addregisterModal = true
    },
    // 提交
    async submitEvent(e) {
      const conRes = await UpdateSmsPass(e.data)
      if (conRes.Error === 0) {
        this.form.name = ''
        this.form.fcode = ''
        this.form.pass = ''
        this.form.newpass = ''
        this.form.phone = ''

        this.$message({
          message: conRes.Message,
          type: 'success'
        })
        this.getCodeText = '获取验证码'
        clearInterval(this.Timer) // 清除该函数
        this.addregisterModal = false
        // window.location.reload()
      } else {
        this.$message({
          message: conRes.Message,
          type: 'error',
          duration: '5000'
        })
      }
    },

    async  codeMsg(data) {
      const conRes = await getsmsCode(data)
      if (conRes.Error !== 0) {
        this.$message({
          message: conRes.Message,
          type: 'error',
          duration: '5000'
        })
        return
      }
    },
    // 获取验证码
    getCode() {
      if (this.form.name === '') {
        this.$message({
          message: '账号不能为空',
          type: 'error'
        })
        return
      }
      if (this.form.phone === '') {
        this.$message({
          message: '手机号不能为空',
          type: 'error'
        })
        return
      }

      var regMoblie = /^1[345678]\d{9}$/
      if (!regMoblie.test(this.form.phone)) {
        this.$message({
          message: '该手机号格式错误',
          type: 'error'
        })
        return
      }

      // 调用短信接口
      // this.disabled = true
      // this.getCodeText = '发送中...' // 发送验证码
      setTimeout(async() => {
        // 调用短信接口
        // this.codeMsg(this.form)
        const conRes = await getsmsCode(this.form)
        if (conRes.Error !== 0) {
          this.$message({
            message: conRes.Message,
            type: 'error',
            duration: '5000'
          })
          return
        }
        this.$message({
          message: '验证码已发送',
          type: 'success'
        })

        this.setTimer() // 调用定时器方法
      }, 1000)
    },

    setTimer() {
      let holdTime = 60 // 定义变量并赋值
      this.getCodeText = '重新获取(' + holdTime + ')'
      this.Timer = setInterval(() => {
        if (holdTime <= 0) {
          this.disabled = false
          this.getCodeText = '获取验证码'
          clearInterval(this.Timer) // 清除该函数
          return // 返回前面
        }
        this.getCodeText = '重新获取(' + holdTime + ')'
        holdTime--
      }, 1000)
    },

    showPwd() {
      if (this.pwdType === 'password') {
        this.pwdType = ''
      } else {
        this.pwdType = 'password'
      }
    },
    async getCSData() {
      try {
        // FSetLoginName
        const res = await getCSData({ opername: decodeURIComponent(this.globalDb.fname), fcategory: 'IB', fkey: '', db: this.globalDb.db })
        if (res.Data) {
          this.loginTitleName = res.Data.fsetloginname
          localStorage.setItem('setConfigData', JSON.stringify(res.Data))
        }
      } catch (error) {
        console.log(error)
      }
    },

    async getConfig() {
      try {
        const conRes = await jichuData()
        localStorage.setItem('fuzhujichuData', JSON.stringify(conRes.Data))
      } catch (error) {
        console.log(error)
      }
    },

    async getAccountingMode() {
      try {
        this.listLoading = true
        const res = await accountingMode()
        this.listLoading = false
        this.accountList = res.Data
      } catch (error) {
        this.listLoading = false
        console.log(error)
      }
    },

    selectZT(value) {
      this.globalDb.ztnamedb = value[0]
      this.globalDb.db = value[1]
    },

    async getClearStorage() {
      try {
        await clearStorage()
      } catch (error) {
        console.log(error)
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(async valid => {
        if (valid) {
          this.loading = true
          try {
            await this.getClearStorage()
            this.loginForm.db = this.globalDb.db
            this.loginForm.ztnamedb = this.globalDb.ztnamedb
            const res = await this.$store.dispatch('Login', this.loginForm)

            // 菜单
            const menuRes = await this.$store.dispatch('GETMENUSLIST', {
              db: this.globalDb.db,
              loginname: decodeURIComponent(this.loginForm.username)
            })
            if (menuRes.Error === 1) {
              this.$message({
                showClose: true,
                message: res.Message,
                type: 'error'
              })
              return
            }

            if (res.Error === 0) {
              this.$message({
                message: res.Message,
                type: 'success'
              })
              this.loading = false
              localStorage.setItem('flookSet', res.Data.flookSet)
              // console.log(res, ' res999999999')
              // console.log(this.globalDb.db, ' this.globalDb.db')
              this.globalDb.db = this.loginForm.db
              this.globalDb.fname = res.Data._is_auth
              localStorage.setItem('setMenuData', JSON.stringify(menuRes.Data))

              this.$router.push({ path: '/' })
            } else {
              this.$message({
                showClose: true,
                message: res.Message,
                type: 'error'
              })
              return
            }

            // console.log(res, ' res')
          } catch (error) {
            // this.$message({
            //   showClose: true,
            //   message: '用户名或者密码不正确!',
            //   type: 'error'
            // })
            // this.$message({
            //   showClose: true,
            //   type: 'error'
            // })
            // console.log('11 error submit!!')
            this.loading = false
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
$bg:#2d3a4b;
$light_gray:#eee;

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      &:-webkit-autofill {
        -webkit-box-shadow: 0 0 0px 1000px rgb(40, 52, 67) inset !important;
        -webkit-text-fill-color: #fff !important;
        caret-color: #fff !important;
      }
    }
  }
  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 5px;
  }
  .account {
    .el-input {
      width: 100%;
    }
  }
}

</style>

<style rel="stylesheet/scss" lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#bacde0;
$light_gray:#0b1a32;

.login-container {
    min-width: 800px;
    min-height: 712px;
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
  .bg-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: url(../../assets/pc.jpg);
    background-repeat: no-repeat;
    background-size: 100% 100%;
  }
  .custom {
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    min-width: 800px;
    min-height: 712px;
    overflow: hidden;
    .login-box {
      position: absolute;
      transform: rotate(0deg);
      opacity: 1;
      left: 50%;
      top: 25%;
      transform: translate(-50%,-25%);
      width: 444px;
      height: 540px;
    }
  }
  .forgot{
     font-size: 10px;
     color: #ccc ;
     cursor:pointer ;

    }

  .login-form {

    position: absolute;
    display: block;
    max-width: 420px;
    width: 100%;
    padding: 20px 35px 15px 35px;
    margin: 0px auto 120px;
    left: 50%;
    top: 20%;
    transform: translate(-50%,-25%);
    z-index: 99;

    .login-btn {
      width:100%;
      background-color: rgb(11, 26, 50);
      border-radius: 5px;
      text-align: center;
      color: rgb(186, 205, 224);
    }
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
    &_login {
      font-size: 30px;
    }
    &_pwd {
      font-size: 20px;
    }
  }
  .title {
    font-size: 26px;
    font-weight: 400;
    color: $light_gray;
    margin: 0px auto 40px auto;
    text-align: center;
    font-weight: bold;
    h4 {
      color: #fff;
      font-size: 22px;
      font-weight: 400;
      height: 20px;
      line-height: 20px;
      margin: 10px 0;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .my-fcode .vxe-input:deep() .vxe-input--suffix {
  width: 60px;
  height: 32px;

  top: 1px;
  text-align: center;
  border-left: 1px solid #dcdfe6;
  background-color: #f5f7fa;
  cursor: pointer;
}

}
</style>
